<?php

namespace app\service;

use app\exception\ParameterException;
use app\model\Member;
use app\utils\Jwt;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
class MemberTokenService
{
    protected $code;
    protected $appID;
    protected $loginUrl;

    protected  $member;

    protected $appSecret;

    public function __construct($code)
    {

        $this->code = $code;
        $this->appID = Config::get('wechat.AppID');
        $this->appSecret= Config::get('wechat.AppSecret');
        $this->loginUrl = sprintf(Config::get('wechat.LoginUrl'),$this->appID,$this->appSecret,$this->code);
        $this->member = new Member();
    }

    public function getToken($pid=0){
        $result = curl_get($this->loginUrl);
        $WxResult = json_decode($result, true);
        if(empty($WxResult)) throw new ParameterException('获取session_key及openID异常,微信内部错误');

        if(array_key_exists('errcode',$WxResult)) throw new ParameterException($WxResult['errmsg']);

        if(!empty($pid)) $WxResult['pid']=$pid;
        return $this->grantToken($WxResult);
    }

    private function grantToken($WxResult){
        $openId = $WxResult['openid'];
        //查看该openID是否存在
        $user = $this->member->where('openid',$openId)->find();

        //存在不做处理 不存在 新增一条记录
        $user = !empty($user) ? $user : $this->newMember($WxResult);

        // 获取JWT配置参数
        $secret = env('jwt.api_secret','');
        $expire = env('jwt.api_expires',0);

        // 生成JWT令牌
        $token = Jwt::generateToken($user->id, $user->username, $secret, $expire);

        // 使用文件缓存，将令牌与用户ID关联并设置过期时间
        Cache::store('file')->set($token, $token, $expire);

        // 返回生成的JWT令牌和用户信息
        return [
            "token"=>$token,
            "username" => $user->username,
            "nickname"=> $user->nickname
        ];

        return $token;
    }

    public function newMember($WxResult)
    {

        $param = [
            'openid' => $WxResult['openid'],
            'session_key' => $WxResult['session_key'],
            'invitation_code' => (new MemberService())->generateInvitationCode(),
            //'username' => $WxResult['openid'],
            'password' =>  password_hash('123456',PASSWORD_DEFAULT),
            'status'=>1,
            'pid' => empty($WxResult['pid']) ? 0 : $WxResult['pid']
        ];

        $param['nickname'] = "微信用户".$param['invitation_code'];
        $param['username'] = $param['invitation_code'];

        return $this->member->allowField(['username', 'password', 'phone','status','nickname','pid'])->create($param);

    }

}
